local skill = fk.CreateSkill {
  name = "lvshi__duel_skill",
}

local ls = require "packages/lvshi/utility"

local skill = fk.CreateSkill {
  name = "lvshi__duel_skill",
}

skill:addEffect("cardskill", {
  prompt = "#lvshi__duel_skill",
  mod_target_filter = function(self, player, to_select, selected, card)
    return to_select ~= player
  end,
  target_filter = Util.CardTargetFilter,
  target_num = 1,
  on_use = function(self, room, use)
    local choice = ls.strategytrickuse(use.from, use.card, "duel_scheme", "duel_courage")
    use.extra_data = use.extra_data or {}
    use.extra_data.strategy = choice
  end,
  on_effect = function(self, room, effect)
    local to = effect.to
    local from = effect.from
    local responsers = { to, from }
    local currentTurn = 1
    local currentResponser = to
    local pattern = "slash"
    local prompt = "#AskForResponseMultiCard:::slash:"
    if effect.extra_data.strategy == "duel_scheme" then
      pattern = ".|.|.|.|.|trick"
      prompt = "#AskForResponseMultiCard:::trick:"
    end

    while currentResponser:isAlive() do
      local loopTimes = effect:getResponseTimes(currentResponser)

      local respond
      for i = 1, loopTimes do
        local params = { ---@type AskToUseCardParams
          skill_name = pattern,
          pattern = pattern,
          cancelable = true,
          event_data = effect
        }
        if loopTimes > 1 then
          params.prompt = prompt..i..":"..loopTimes
        end
        respond = room:askToResponse(currentResponser, params)
        if respond then
          room:responseCard(respond)
        else
          break
        end
      end

      if not respond then
        break
      end

      currentTurn = currentTurn % 2 + 1
      currentResponser = responsers[currentTurn]
    end

    if currentResponser:isAlive() then
      local damage = 1
      if effect.extra_data.strategy == "duel_courage" then
        if table.every(room.alive_players, function (p) return p.hp >= effect.from.hp end) then
          damage = damage + 1
        end
      end
      room:damage({
        from = responsers[currentTurn % 2 + 1],
        to = currentResponser,
        card = effect.card,
        damage = damage,
        damageType = fk.NormalDamage,
        skillName = skill.name,
      })
    end
  end,
})

return skill